package com.ruoyi.projectAch.utils;

public class FilenameSanitizerUtils {

    // Regular expression that matches whitespace and characters illegal in Windows and Linux filenames.
    private static final String ILLEGAL_CHARACTERS_REGEX = "[\\s<>:\"/\\\\|?*\\x00-\\x1F]+";

    /**
     * Sanitizes the input string to be a valid filename on Linux and Windows.
     * It removes all illegal characters and whitespace, and truncates the string to 50 characters if necessary.
     *
     * @param input The input string to sanitize.
     * @return A sanitized string suitable for use as a filename.
     */
    public static String sanitizeFilename(String input) {
        if (input == null || input.isEmpty()) {
            return "";
        }

        // Remove all illegal characters and whitespace
        String sanitized = input.replaceAll(ILLEGAL_CHARACTERS_REGEX, "");

        // Truncate the string to the first 50 characters if it's too long
        return sanitized.length() > 50 ? sanitized.substring(0, 50) : sanitized;
    }

    // Example usage
    public static void main(String[] args) {
        String originalFilename = "example file name with illegal <>:\"/\\|?* and whitespace \r\n\t";
        String sanitizedFilename = sanitizeFilename(originalFilename);
        System.out.println("Sanitized Filename: " + sanitizedFilename);
    }
}
